package io.renren.modules.job.task.pdf;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.data.domain.Example;

import com.itextpdf.text.DocumentException;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.StrFormatter;
import io.renren.modules.app.entity.Bx;
import io.renren.modules.app.entity.BxMx;
import io.renren.modules.app.entity.nosql.LcPdfTemplate;
import io.renren.modules.app.entity.nosql.PdfInfo;
import io.renren.modules.app.nosql.mongo.IPdfRepo;
import io.renren.modules.app.service.IBxMxService;
import io.renren.modules.app.service.IBxService;
import io.renren.modules.app.utils.FkUtil;
import io.renren.modules.app.utils.GoFastdfs;
import io.renren.modules.app.utils.GoFastdfs.Result;
import io.renren.modules.app.utils.PathUtil;
import io.renren.modules.app.utils.PdfUtil;
import io.renren.modules.job.task.TaskPdf;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Data
@Slf4j
@AllArgsConstructor
public class PdfBx implements IPdf {
	// 流程id
	private String bizKey;
	// 要生成pdf的路径
	private File pdf;
	private String process;
	private Map<String, Object> params;
	private IPdfRepo pdfRepo;
	private IBxService bxService;
	private IBxMxService bxMxService;
	private LcPdfTemplate lcTemplate;

	@Override
	public void gen() throws IOException, DocumentException, com.lowagie.text.DocumentException {
		Bx bx = bxService.findById(bizKey).get();
		params.put("bx", bx);
		List<BxMx> mxs = bxMxService.findMxByWaijianId(bx.getId());
		List<String> mxsStr = new ArrayList<>();
		mxs.forEach(mx -> {
			mxsStr.add(StrFormatter.format(
					"<tr><td colspan='2'>出发地点:{} 出发日期:{} 到达地点:{} 达到日期:{} 人数:{} 交通工具:{} 交通费金额:{} 餐费天数:{} 餐费金额:{} 其他补助:{} 天数:{} 金额:{} 小计:{}</td></tr>",
					mx.getChuFadiDain(), mx.getChufaRiqi(), mx.getDaoDaDidian(), mx.getDaoDaRiqi(), mx.getRenShu(), mx.getJiaoTongGongju(),
					mx.getJiaoTongMoney(), mx.getCanFeiTianShu(), mx.getCanFieMoney(), mx.getQiTaBuzhu(), mx.getTianshu(), mx.getMoney(),
					mx.getXiaoji()));
		});
		String join = CollUtil.join(mxsStr, " ");
		log.info(join);
		params.put("mx", join);

		
		String content = new FkUtil(params, lcTemplate).render();
		String picPath = "file:/" + PathUtil.getCurrentPath() + "/logo.png";

		if (new PdfUtil(pdf, picPath).createPdf(content)) {
			if (!pdfRepo.findOne(Example.of(new PdfInfo().setName(pdf.getName()))).isPresent()) {
				GoFastdfs goFastdfs = new GoFastdfs(TaskPdf.fileServer, "pdf", "pdf");
				Result upload = goFastdfs.upload(pdf);
				
				pdfRepo.save(new PdfInfo(pdf.getName(), process, upload.getPath()));
				
			}
		}
	}
}